package com.ruoyi.project.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
//import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ruoyi.common.utils.AlibabaApi;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.project.system.domain.SysPayOrder;
import com.ruoyi.project.system.domain.SysProduct;
import com.ruoyi.project.system.domain.SysQuery;
import com.ruoyi.project.system.mapper.SysPayOrderMapper;
import com.ruoyi.project.system.service.ISysPayOrderService;
import com.ruoyi.project.system.service.ISysProductService;
import com.ruoyi.project.system.service.ISysQueryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 进件查询支付Service业务层处理
 */
@Slf4j
@Service
public class SysPayOrderServiceImpl implements ISysPayOrderService {

    @Autowired
    private ISysQueryService iSysQueryService;

    @Autowired
    private ISysProductService iSysProductService;

    @Autowired
    private SysPayOrderMapper sysPayOrderMapper;

    @Value("${back-domain}")
    private String backDomain;

    @Value("${front-domain}")
    private String frontDomain;

    public static String[] paths = {"bdp", "bd", "com", "check", "jud", "imm"};

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int refund(SysPayOrder sysPayOrder) throws Exception {
        SysPayOrder pay = sysPayOrderMapper.selectSysPayOrderByOrderNo(sysPayOrder.getOrderNo());
        SysPayOrder refund = new SysPayOrder(sysPayOrder.getOrderNo(),"REFUND");
        refund.setRemark(sysPayOrder.getRemark());
        sysPayOrderMapper.updateSysPayOrder(refund);

//        AlipayTradeRefundResponse refundResponse = AlibabaApi.refund(sysPayOrder);
//        if ("10000".equals(refundResponse.getCode()) && "Success".equals(refundResponse.getMsg())) {
            return 1;
//        }else {
//            throw new Exception(refundResponse.getSubMsg());
//        }
    }

    @Override
    @Transactional
    public JSONObject createPayInfo(SysPayOrder sqp) throws IOException {
        // 1 拉起进件订单
        SysQuery sysQuery = iSysQueryService.selectSysQueryById(Long.parseLong(sqp.getOutId()));
        // 2 拉起产品价格信息
//        Promote promote = iSysProductService.calculatePriceInfo(sysQuery.getUserId(), sysQuery.getProductId());
        // 3 合成支付订单
        sqp = makeQueryPay(sqp, sysQuery, null);
        // 4 保存
        insertSysPayOrder(sqp);
        // 5 拉起支付
        JSONObject zhifuFM = zhifuFM(sqp, paths[sysQuery.getProductId() - 1]);
//        JSONObject zhifuFM = null;
        return zhifuFM;
    }

    public SysPayOrder makeQueryPay(SysPayOrder sqp, SysQuery sysQuery, SysProduct promote) {
//        sqp.setSysFloorPrice(promote.getSysFloorPrice());
//        sqp.setRoyalty(promote.getRoyalty());
//        sqp.setFloorPrice(promote.getFloorPrice());
//        sqp.setBrokerage(promote.getBrokerage());
//        sqp.setPricing(promote.getPricing());
//        sqp.setRedPacketNum(promote.getRedPacketNum());
//        sqp.setPayState("NOTPAY");
//        sqp.setPayType("alipaysign");
//        sqp.setSubject(promote.getProductName());
//        sqp.setBody(promote.getProductId() + "");

        String key = StringUtils.isNotEmpty(sysQuery.getName()) ? sysQuery.getName() + "::" : "";
        key += StringUtils.isNotEmpty(sysQuery.getCardNo()) ? sysQuery.getCardNo() + "::" : "";
        key += StringUtils.isNotEmpty(sysQuery.getMobile()) ? sysQuery.getMobile() + "::" : "";
        key = key.substring(0, key.length() - 2);

        return sqp;
    }

    public JSONObject zhifuFM(SysPayOrder sqp, String path) throws IOException {
//      容易查
        String merchantNum = "1394150425178931200";             // 商户号
        String secretKey = "086951d2cdb0b467c553b507d6f866db";  // 商户密钥
        String sign = merchantNum + sqp.getOrderNo() + sqp.getPricing() + backDomain + secretKey;
        sign = Md5Utils.hash(sign);                             // md5签名
        Map<String, String> paramMap = new HashMap<>();         // post请求的参数
        paramMap.put("merchantNum", merchantNum);
        paramMap.put("orderNo", sqp.getOrderNo());
        paramMap.put("amount", sqp.getPricing().toString());
        paramMap.put("notifyUrl", backDomain);    // 填写您的接收支付成功的异步通知地址
        paramMap.put("returnUrl", frontDomain + path);

        paramMap.put("payType", sqp.getPayType());
        paramMap.put("sign", sign);
        paramMap.put("subject", "tianqi");
        log.info("支付请求参数：" + paramMap);
        String result;
        JSONObject ret = new JSONObject();
        String paramStr = StringUtils.toParams(paramMap);

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost httpost = new HttpPost("http://api-albd2vor5wqo.zhifu.fm.it88168.com/api/startOrder?" + paramStr); // 设置响应头信息
        String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";
        httpost.setHeader("User-Agent", userAgent);     //防止被防火墙拦截 Apache httpclient
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(5000).build();
        httpost.setConfig(requestConfig);
        HttpResponse retResp = httpclient.execute(httpost);
        result = EntityUtils.toString(retResp.getEntity(), "UTF-8");
        if (result.startsWith("{")) { //为了您的业务健壮性，建议简单判断或者增加下容错逻辑
            ret = JSONObject.parseObject(result);
        } else {
            ret.put("code", "error");
            ret.put("result", result);
            ret.put("msg", "发起支付订单失败，接口返回信息异常");
        }
        return ret;
    }

    /**
     * 查询进件查询支付
     *
     * @param orderNo 进件查询支付主键
     * @return 进件查询支付
     */
    @Override
    public SysPayOrder selectSysPayOrderByOrderNo(String orderNo) {
        return sysPayOrderMapper.selectSysPayOrderByOrderNo(orderNo);
    }

    /**
     * 查询进件查询支付列表
     *
     * @param SysPayOrder 进件查询支付
     * @return 进件查询支付
     */
    @Override
    public List<SysPayOrder> selectSysPayOrderList(SysPayOrder SysPayOrder) {
        return sysPayOrderMapper.selectSysPayOrderList(SysPayOrder);
    }

    /**
     * 新增进件查询支付
     *
     * @param SysPayOrder 进件查询支付
     * @return 结果
     */
    @Override
    public int insertSysPayOrder(SysPayOrder SysPayOrder) {
        return sysPayOrderMapper.insertSysPayOrder(SysPayOrder);
    }

    /**
     * 修改进件查询支付
     *
     * @param SysPayOrder 进件查询支付
     * @return 结果
     */
    @Override
    public int updateSysPayOrder(SysPayOrder SysPayOrder) {
        return sysPayOrderMapper.updateSysPayOrder(SysPayOrder);
    }

    /**
     * 批量删除进件查询支付
     *
     * @param orderNos 需要删除的进件查询支付主键
     * @return 结果
     */
    @Override
    public int deleteSysPayOrderByOrderNos(String[] orderNos) {
        return sysPayOrderMapper.deleteSysPayOrderByOrderNos(orderNos);
    }

}
